﻿using NewLife.Caching;
using NewLife.Log;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace NewLifeRedisDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var rds = Redis.Create("192.168.0.201:6379", 0);
            // 调试日志。正式使用时注释
            rds.Log = XTrace.Log;
            // 注册全部功能,没有这句代码就只有基本功能
            FullRedis.Register();
            XTrace.UseConsole();

            // 设置
            var user = new User() { Name = "Ken", Age = 18 };
            rds.Set("NewLifeRedisDemo:user", user, 3600);
            // 获取
            var user2 = rds.Get<User>("NewLifeRedisDemo:user");
            Console.WriteLine("Name: {0}", user2.Name);
            Console.WriteLine("Json: {0}", rds.Get<String>("NewLifeRedisDemo:user"));
            // 判断
            if (rds.ContainsKey("NewLifeRedisDemo:user"))
                Console.WriteLine("存在！");
            // 删除
            rds.Remove("user");
            // 自增
            rds.Set("NewLifeRedisDemo:count", 1);
            rds.Increment("NewLifeRedisDemo:count", 1);
            Console.WriteLine("count: {0}", rds.Get<int>("NewLifeRedisDemo:count"));
            // 批量设置
            var dic = new Dictionary<string, Object>()
            {
                ["NewLifeRedisDemo:all_name"] = "Harry",
                ["NewLifeRedisDemo:all_time"] = DateTime.Now,
                ["NewLifeRedisDemo:all_title"] = "Title",
            };
            rds.SetAll(dic);
            // 批量获取
            var vs = rds.GetAll<String>(dic.Keys);
            Console.WriteLine(vs.Join(",", e => $"{e.Key}={e.Value}"));

            // 列表，Add就会保存到Redis
            var list = rds.GetList<User>("NewLifeRedisDemo:list2");
            list.Add(new User { Name = "a", Age = 18 });
            list.Add(new User { Name = "b", Age = 19 });

            // 字典
            var dic2 = rds.GetDictionary<DateTime>("NewLifeRedisDemo:dic2");
            dic2.Add("xxx", DateTime.Now);
            dic2.Add("yyy", DateTime.UtcNow);
            dic2.Add("zzz", DateTime.UtcNow);
            dic2.Remove("zzz");
            Console.WriteLine(dic2["xxx"].ToFullString());

            // 队列
            var mq = rds.GetQueue<String>("NewLifeRedisDemo:queue");
            mq.Add(new[] { "a", "b", "c", "d" });
            var arr = mq.Take(3);   // Take操作后，会删除Ridis对应数据
            Console.WriteLine(arr.Join(","));

            // 集合
            var set = rds.GetSet<String>("NewLifeRedisDemo:set");
            set.Add("20190708-1");
            set.Add("20190708-2");
            set.Add("20190708-3");
            set.Add("20190708-3");
            Console.WriteLine(set.Count);
            Console.WriteLine(set.Contains("20190708-3"));


            Console.WriteLine("共有缓存对象 {0} 个", rds.Count);



            Console.ReadKey();

        }
    }

    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
